<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>

<div class="callout callout-left">
  <span class="callout-title text-muted">应用管理</span>
  <!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
  <button class="btn btn-primary" id="create_app" data-toggle="modal" data-target="#myModal" style="margin-left: 35px;">
    <span class="glyphicon glyphicon-plus-sign">&nbsp;添加应用</span></button>
</div>


<div class="callout callout-white">
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
      <tr>
        <th>编号</th>
        <th>应用名称</th>
        <th>语言</th>
        <th>描述</th>
        <th>删除</th>
      </tr>
      </thead>
      <tbody id="downloads_content">
      </tbody>
    </table>
  </div>
</div>

<script>
require.config({
  baseUrl: '<%=path %>/js',
  paths: {
    jquery: 'jquery-1.9.1.min',
    common: 'common',
    upload: 'ajaxfileupload',
    bootstrapswitch: 'bootstrap-switch.min'
  }
});

require(['jquery', 'common', 'upload', 'bootstrapswitch'], function ($, common) {
//console.log("商品管理模块载入");

var workspace = function () {

  var domKey;
  var dataOpt;
  var downloads;

  var init = function () {
    domKey = common.commData.domKey;
    dataOpt = common.dataOpt;

    _initTable();
    _addApp();
  }

  var _initTable = function () {
    downloads = common.ajaxLoadData(dataOpt.downloadOpt) || [];

    var template = "<tr><th>#row#</th>" +
      "<td>#appName#</td>" +
      "<td>#language#</td>" +
      "<td style='max-width:450px;white-space:normal;'>#desc#</td>" +
      "<td>" +
      "<a href='#myModal' class='editApp' data-toggle='modal' data-name='#appName#'><span class='glyphicon glyphicon-edit text-primary'>编辑</span></a>" +
      "&nbsp;&nbsp;<a href='#myModal' class='delApp' data-toggle='modal' data-name='#appName#'><span class='glyphicon glyphicon-remove text-primary'>删除</span><a></td></tr>";

    var row = 1;
    var html = "";
    var thisT = "";
    downloads.forEach(function (download) {
      thisT = template;
      thisT = thisT.replace(/#row#/g, row++).replace(/#appName#/g, download["appName"]).replace(/#language#/g, download["appLanguage"])
          .replace(/#desc#/g, download["webDesc"]);
      html += thisT;
    });

    $("#downloads_content").html(html);
    delApp();
    editApp();
  }

  // 添加应用
  var _addApp = function () {
    var modalBodyTemplate = "<form class='form-horizontal' role='form'>" +
      "<div class='form-group'>" +
      "<label for='appName' class='col-sm-3 control-label'>应用名称</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='appName' name='appName' placeholder='应用名称' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='picurl' class='col-sm-3 control-label'>软件图片</label>" +
      "<div class='col-sm-9'>" +
      "<input type='file' accept='image/png, image/jpeg, image/gif, image/jpg' name='picurl' id='picurl' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='language' class='col-sm-3 control-label'>语言</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' name='language' id='language'>" +
      "<option value='中文'>中文</option>" +
      "<option value='英文'>英文</option>" +
      "</select></div></div>" +
      "<div class='form-group'>" +
      "<label for='inner32' class='col-sm-3 control-label'>校内32位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input  class='form-control' name='inner32' id='inner32' placeholder='校内32位下载地址'/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='inner64' class='col-sm-3 control-label'>校内64位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='inner64' name='inner64' placeholder='校内64位下载地址' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='outer32' class='col-sm-3 control-label'>校外32位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='outer32' name='outer32' placeholder='校外32位下载地址' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='outer64' class='col-sm-3 control-label'>校外64位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='outer64' name='outer64' placeholder='校外64位下载地址'/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='desc' class='col-sm-3 control-label'>描述信息(100字)</label>" +
      "<div class='col-sm-9'>" +
      "<textarea class='form-control' id='desc' name='desc' row='3' placeholder='100字以内'></textarea>" +
      "</div></div></form>";

    $("#create_app").click(function () {
      common.cleanModal();
      domKey.modal.find(".modal-dialog");
      domKey.modalLabel.html("添加应用");
      domKey.modalBody.html(modalBodyTemplate);


      domKey.modalAct.html("保存")
      .click(function () {
        common.disable(domKey.modalAct);// 提交请求则禁掉按钮
        var data = {
          "appName": $("#appName").val(),
          "picUrl": "",
          "language": $("#language").val(),
          "inner32": $("#inner32").val(),
          "outer32": $("#outer32").val(),
          "inner64": $("#inner64").val(),
          "outer64": $("#outer64").val(),
          "desc": $("#desc").val()
        }

        // 添加应用信息
        var doApp = function () {
              $.ajax({
                url: "<%=path %>/servlet/soft/AddDownloadServlet",
                type: "post",
                data: data,
                dataType: "json",
                async: false,
                success: function (data) {
                  if ("1" === data["retCode"]) {

                  } else {
                    alert(data["desc"]);
                  }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                  alert("AddDownloadServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState + ":" + textStatus);
                },
                complete: function () {
                  domKey.modal.find(".close").click();
                  _initTable();
                }
              });
            }

        if (data["appName"].length === 0) {
          alert("请填写应用名称");
          common.enable(domKey.modalAct);
        } else if (data["desc"].length > 99) {
          alert("描述超出字数");
          common.enable(domKey.modalAct);
        } else if (typeof($("#picurl")[0].files[0]) === "undefined") {
          alert('请选择图片');
          common.enable(domKey.modalAct);
        } else {
          // 图片上传，并返回图片相对路径
          $.ajaxFileUpload({
            url: "<%=path %>/servlet/UploadPicServlet",
            secureuri: false,
            fileElementId: "picurl",
            dataType: "json",
            data: {},
            success: function (rdata, status) {
              data["picUrl"] = rdata.relaPath;
              doApp();
            },
            error: function (data, status, e) {
              alert("上传出错，新建应用失败");
            },
            complete: function () {
              domKey.modal.find(".close").click();
            }
          });
        }
      });
    });
  }

  // 编辑
  var editApp = function () {
    var modalBodyTemplate = "<form class='form-horizontal' role='form'>" +
      "<div class='form-group'>" +
      "<label for='appName' class='col-sm-3 control-label'>应用名称</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='appName' name='appName' readonly />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='' class='col-sm-3 control-label'>软件图片</label>" +
      "<div class='col-sm-9'>" +
      "<label class='checkbox-inline'>" +
      "<input type='checkbox' name='isChange' id='isChange' />更改图片</label>" +
      "<div id='picfile' style='display:inline-block;left:15px;top:5px;position:relative;'></div></div></div>" +
      "<div class='form-group'>" +
      "<label for='language' class='col-sm-3 control-label'>语言</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' name='language' id='language'>" +
      "<option value='中文'>中文</option>" +
      "<option value='英文'>英文</option>" +
      "</select></div></div>" +
      "<div class='form-group'>" +
      "<label for='inner32' class='col-sm-3 control-label'>校内32位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input  class='form-control' name='inner32' id='inner32' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='inner64' class='col-sm-3 control-label'>校内64位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='inner64' name='inner64' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='outer32' class='col-sm-3 control-label'>校外32位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='outer32' name='outer32' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='outer64' class='col-sm-3 control-label'>校外64位版本</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' id='outer64' name='outer64' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='desc' class='col-sm-3 control-label'>描述信息(100字)</label>" +
      "<div class='col-sm-9'>" +
      "<textarea class='form-control' id='desc' name='desc' row='3' placeholder='100字以内'></textarea>" +
      "</div></div></form>";

    $(".editApp").each(function () {
      var softName = $(this).data("name");
      $(this).click(function () {
        common.cleanModal();
        domKey.modalLabel.html("编辑应用");
        domKey.modalBody.html(modalBodyTemplate);

        $("#isChange").change(function () {
          if ($(this).is(":checked")) {// 更改图片
            $("#picfile").html("<input type='file' accept='image/png, image/jpeg, image/gif, image/jpg' name='picurl' id='picurl' />");
          } else {
            $("#picfile").html("");
          }
        });

        backfillData(softName);// 数据回填

        domKey.modalAct.html("保存")
        .click(function () {
              common.disable(domKey.modalAct);// 提交请求则禁掉按钮
              var data = {
                "appName": $("#appName").val(),
                "picUrl": $("#isChange").val(),
                "language": $("#language").val(),
                "inner32": $("#inner32").val(),
                "outer32": $("#outer32").val(),
                "inner64": $("#inner64").val(),
                "outer64": $("#outer64").val(),
                "desc": $("#desc").val()
              }

              var doEdit = function () {
                if (data["desc"].length > 99) {
                  alert("描述超出字数");
                  common.enable(domKey.modalAct);
                } else {
                  $.ajax({
                    url: "<%=path %>/servlet/soft/EditDownloadServlet",
                    type: "post",
                    data: data,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                      if ("1" == data["retCode"]) {

                      } else {
                        alert(data["desc"]);
                      }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                      alert("EditDownloadServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState + ":" + textStatus);
                    },
                    complete: function () {
                      domKey.modal.find(".close").click();
                      _initTable();
                    }
                  });
                }
              }

              if ($("#isChange").is(":checked")) {
                if (typeof($("#picurl")[0].files[0]) == "undefined") {
                  alert('请选择图片');
                  common.enable(domKey.modalAct);
                } else {
                  // 图片上传，并返回图片相对路径
                  $.ajaxFileUpload({
                    url: "<%=path %>/servlet/UploadPicServlet",
                    secureuri: false,
                    fileElementId: "picurl",
                    dataType: "json",
                    data: {},
                    success: function (rdata, status) {
                      data["picUrl"] = rdata.relaPath;
                      doEdit();
                    },
                    error: function (data, status, e) {
                      alert("上传出错，编辑应用失败");
                    },
                    complete: function () {
                      domKey.modal.find(".close").click();
                    }
                  });
                }
              } else {
                doEdit();
              }
            });
      });
    });

    var backfillData = function (softName) {
      for (var i = 0, n = downloads.length; i < n; i++) {
        if (downloads[i]["appName"] == softName) {
          $("#appName").val(downloads[i]["appName"]);
          $("#isChange").val(downloads[i]["appPicURL"]);
          $("#language").val(downloads[i]["appLanguage"]);
          $("#inner32").val(downloads[i]["inner32"]);
          $("#inner64").val(downloads[i]["inner64"]);
          $("#outer32").val(downloads[i]["outer32"]);
          $("#outer64").val(downloads[i]["outer64"]);
          $("#desc").val(downloads[i]["webDesc"]);
          break;
        }
      }
    }
  }

  // 删除商品
  var delApp = function () {
    var modalBodyTemplate = "<span class='glyphicon glyphicon-info-sign' style='color:#FF8A00;font-size:26px;margin-right:15px;top:7px;'></span>确认删除#name#？";
    $(".delApp").each(function () {
      var appName = $(this).data("name");
      $(this).click(function () {
        common.cleanModal();
        domKey.modal.find(".modal-dialog").addClass("modal-sm");
        var thisTemplate = modalBodyTemplate;
        thisTemplate = thisTemplate.replace(/#name#/g, appName);
        domKey.modalLabel.html("删除应用");
        domKey.modalBody.html(thisTemplate);

        domKey.modalAct.html("确认")
        .on("click", function () {
          common.disable(domKey.modalAct);// 提交请求则禁掉按钮

          $.ajax({
            url: "<%=path %>/servlet/soft/DelDownloadServlet",
            type: "post",
            data: {"appName": appName},
            dataType: "json",
            async: false,
            success: function (data) {
              if ("1" === data["retCode"]) {

              } else {
                alert(data["desc"]);
              }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              alert("DelDownloadServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState + ":" + textStatus);
            },
            complete: function () {
              domKey.modal.find(".close").click();
              _initTable();// 刷新表格
            }
          });
        });
      });
    });
  }

  return {
    init: init
  }
}();

$(function () { workspace.init(); });

});

requirejs.onError = function (err) {
  console.error(err);
  if (err.requireType === 'timeout') {
    console.error('modules: ' + err.requireModules);
  }
  throw err;
}
</script>
